package com.lin.missyou.repository;

import com.lin.missyou.model.UserCoupon;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;

public interface UserCouponRepository extends JpaRepository<UserCoupon,Long> {

    Optional<UserCoupon> findByUserIdAndCouponIdAndStatus(Long userId,Long couponId,Integer status);
    Optional<UserCoupon> findByUserIdAndCouponId(Long userId,Long couponId);

    @Modifying
    @Query("update UserCoupon uc set \n" +
            "uc.status = 2,uc.orderId = :oid\n" +
            "where uc.couponId = :couponId\n" +
            "and uc.userId = :uid\n" +
            "and uc.status = 1\n" +
            "and uc.orderId is null")
    int writeOff(Long couponId,Long oid,Long uid);


    @Modifying
    @Query("update UserCoupon uc\n" +
            "set uc.status = 1,uc.orderId = null \n" +
            "where uc.userId = :uid\n" +
            "and uc.couponId = :couponId")
    int returnBack(Long uid,Long couponId);
}
